<template>
  <div class="profit-loss-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><TrendCharts /></el-icon>
          <div class="header-text">
            <h2>盈亏分析</h2>
            <p>库存盘点盈亏数据分析</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出报表
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 汇总统计 -->
    <div class="summary-row">
      <el-card shadow="hover" class="summary-card profit">
        <div class="summary-content">
          <div class="summary-icon">
            <el-icon :size="50"><TrendCharts /></el-icon>
          </div>
          <div class="summary-info">
            <div class="summary-label">盘盈总金额</div>
            <div class="summary-value profit-value">+¥{{ stats.totalProfit.toLocaleString() }}</div>
            <div class="summary-desc">{{ stats.profitCount }}笔盘盈</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="summary-card loss">
        <div class="summary-content">
          <div class="summary-icon">
            <el-icon :size="50"><TrendCharts /></el-icon>
          </div>
          <div class="summary-info">
            <div class="summary-label">盘亏总金额</div>
            <div class="summary-value loss-value">-¥{{ stats.totalLoss.toLocaleString() }}</div>
            <div class="summary-desc">{{ stats.lossCount }}笔盘亏</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="summary-card net">
        <div class="summary-content">
          <div class="summary-icon">
            <el-icon :size="50"><DataAnalysis /></el-icon>
          </div>
          <div class="summary-info">
            <div class="summary-label">净盈亏金额</div>
            <div class="summary-value" :class="stats.netAmount >= 0 ? 'profit-value' : 'loss-value'">
              {{ stats.netAmount >= 0 ? '+' : '' }}¥{{ Math.abs(stats.netAmount).toLocaleString() }}
            </div>
            <div class="summary-desc">盈亏率：{{ stats.profitLossRate }}%</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="summary-card">
        <div class="summary-content">
          <div class="summary-icon">
            <el-icon :size="50"><Box /></el-icon>
          </div>
          <div class="summary-info">
            <div class="summary-label">涉及商品</div>
            <div class="summary-value">{{ stats.totalProducts }}</div>
            <div class="summary-desc">{{ stats.totalSheets }}张盘点单</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="任务单号">
          <el-input 
            v-model="searchForm.taskNo" 
            placeholder="任务单号" 
            clearable 
            style="width: 200px"
          >
            <template #append>
              <el-button @click="handleSelectTask">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 280px"
          />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="searchForm.warehouseId" placeholder="全部仓库" clearable style="width: 150px">
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盈亏类型">
          <el-select v-model="searchForm.type" placeholder="全部类型" clearable style="width: 150px">
            <el-option label="盘盈" value="profit" />
            <el-option label="盘亏" value="loss" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 任务筛选提示 -->
      <el-alert
        v-if="searchForm.taskNo"
        :title="`当前筛选：任务单 ${searchForm.taskNo}`"
        type="info"
        :closable="true"
        @close="searchForm.taskNo = ''"
        style="margin-top: 12px;"
      >
        正在查看该任务单的盈亏数据（汇总该任务下所有盘点单的盈亏）
      </el-alert>
    </el-card>

    <!-- 盈亏明细 -->
    <el-card shadow="never">
      <div class="card-header">
        <span>盈亏明细</span>
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="summary">汇总视图</el-radio-button>
          <el-radio-button label="detail">明细视图</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 汇总视图 -->
      <el-table v-if="viewMode === 'summary'" :data="summaryData" stripe border>
        <el-table-column prop="productCode" label="商品编码" width="150" />
        <el-table-column prop="productName" label="商品名称" min-width="200" />
        <el-table-column prop="category" label="商品分类" width="120" />
        <el-table-column prop="checkCount" label="盘点次数" width="100" align="right" />
        <el-table-column prop="totalDiffQty" label="累计盈亏数量" width="150" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.totalDiffQty)">
              {{ row.totalDiffQty > 0 ? '+' : '' }}{{ row.totalDiffQty }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.unitPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalDiffAmount" label="累计盈亏金额" width="180" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.totalDiffAmount)">
              {{ row.totalDiffAmount > 0 ? '+' : '' }}¥{{ Math.abs(row.totalDiffAmount).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lossRate" label="损耗率" width="120" align="right">
          <template #default="{ row }">
            <span :class="row.lossRate > 2 ? 'loss-text' : ''">
              {{ row.lossRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewProduct(row)" size="small">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 明细视图 -->
      <el-table v-else :data="detailData" stripe border>
        <el-table-column prop="sheetNo" label="盘点单号" width="180">
          <template #default="{ row }">
            <el-link type="primary" @click="handleViewSheet(row)">{{ row.sheetNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="checkTime" label="盘点时间" width="180" />
        <el-table-column prop="warehouseName" label="仓库" width="120" />
        <el-table-column prop="productCode" label="商品编码" width="150" />
        <el-table-column prop="productName" label="商品名称" min-width="200" />
        <el-table-column prop="bookQty" label="账面数量" width="100" align="right" />
        <el-table-column prop="actualQty" label="实盘数量" width="100" align="right" />
        <el-table-column prop="diffQty" label="盈亏数量" width="120" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.diffQty)">
              {{ row.diffQty > 0 ? '+' : '' }}{{ row.diffQty }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.unitPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="diffAmount" label="盈亏金额" width="150" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.diffAmount)">
              {{ row.diffAmount > 0 ? '+' : '' }}¥{{ Math.abs(row.diffAmount).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="checkPerson" label="盘点人" width="100" />
        <el-table-column prop="remark" label="原因备注" min-width="150" />
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  TrendCharts, Download, Search, Refresh, DataAnalysis, Box
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 状态
const viewMode = ref('summary')

// 搜索表单
const searchForm = reactive({
  taskNo: '',
  dateRange: null,
  warehouseId: null,
  type: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 统计数据
const stats = reactive({
  totalProfit: 125000,
  profitCount: 45,
  totalLoss: 98500,
  lossCount: 38,
  netAmount: 26500,
  profitLossRate: 1.2,
  totalProducts: 156,
  totalSheets: 28
})

// 仓库数据
const warehouses = ref([
  { id: 1, name: '主仓库' },
  { id: 2, name: '分仓A' },
  { id: 3, name: '分仓B' }
])

// 汇总数据
const summaryData = ref([
  {
    productCode: 'P001',
    productName: 'iPhone 15 Pro Max 256GB',
    category: '手机',
    checkCount: 3,
    totalDiffQty: -12,
    unitPrice: 9999,
    totalDiffAmount: -119988,
    lossRate: 2.4
  },
  {
    productCode: 'P002',
    productName: 'MacBook Pro 14寸 M3',
    category: '笔记本',
    checkCount: 2,
    totalDiffQty: -5,
    unitPrice: 14999,
    totalDiffAmount: -74995,
    lossRate: 1.8
  },
  {
    productCode: 'P003',
    productName: 'AirPods Pro 2',
    category: '耳机',
    checkCount: 4,
    totalDiffQty: 18,
    unitPrice: 1899,
    totalDiffAmount: 34182,
    lossRate: -3.6
  }
])

// 明细数据
const detailData = ref([
  {
    sheetNo: 'CHS202401150001',
    checkTime: '2024-01-15 14:30:00',
    warehouseName: '主仓库',
    productCode: 'P001',
    productName: 'iPhone 15 Pro Max 256GB',
    bookQty: 100,
    actualQty: 95,
    diffQty: -5,
    unitPrice: 9999,
    diffAmount: -49995,
    checkPerson: '张三',
    remark: '发现破损2台，丢失3台'
  },
  {
    sheetNo: 'CHS202401150001',
    checkTime: '2024-01-15 14:30:00',
    warehouseName: '主仓库',
    productCode: 'P002',
    productName: 'MacBook Pro 14寸 M3',
    bookQty: 50,
    actualQty: 48,
    diffQty: -2,
    unitPrice: 14999,
    diffAmount: -29998,
    checkPerson: '张三',
    remark: '账实不符'
  },
  {
    sheetNo: 'CHS202401150001',
    checkTime: '2024-01-15 14:30:00',
    warehouseName: '主仓库',
    productCode: 'P003',
    productName: 'AirPods Pro 2',
    bookQty: 200,
    actualQty: 205,
    diffQty: 5,
    unitPrice: 1899,
    diffAmount: 9495,
    checkPerson: '张三',
    remark: '发现未入库商品5台'
  }
])

// 方法
const handleSearch = () => {
  pagination.page = 1
  ElMessage.success('搜索完成')
}

const handleReset = () => {
  Object.assign(searchForm, {
    taskNo: '',
    dateRange: null,
    warehouseId: null,
    type: ''
  })
  handleSearch()
}

const handleSelectTask = () => {
  if (searchForm.taskNo) {
    ElMessage.success(`筛选任务单：${searchForm.taskNo}`)
    handleSearch()
  }
}

const handlePageChange = () => {
  console.log('分页变化', pagination)
}

const handleViewProduct = (row) => {
  ElMessage.info(`查看商品：${row.productName}`)
}

const handleViewSheet = (row) => {
  router.push(`/inventory/check-detail?sheetNo=${row.sheetNo}`)
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

// 工具函数
const getDiffClass = (value) => {
  if (value > 0) return 'profit-text'
  if (value < 0) return 'loss-text'
  return ''
}
</script>

<style scoped>
.profit-loss-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.summary-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.summary-card {
  cursor: pointer;
  transition: all 0.3s;
}

.summary-card:hover {
  transform: translateY(-4px);
}

.summary-card.profit {
  border-top: 3px solid #67C23A;
}

.summary-card.loss {
  border-top: 3px solid #F56C6C;
}

.summary-card.net {
  border-top: 3px solid #409EFF;
}

.summary-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.summary-icon {
  color: #409EFF;
  opacity: 0.2;
}

.summary-info {
  flex: 1;
}

.summary-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.summary-value.profit-value {
  color: #67C23A;
}

.summary-value.loss-value {
  color: #F56C6C;
}

.summary-desc {
  font-size: 13px;
  color: #909399;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.profit-text {
  color: #67C23A;
  font-weight: 500;
}

.loss-text {
  color: #F56C6C;
  font-weight: 500;
}
</style>

